
package com.borqs.music.ui;

import static com.borqs.music.tasks.UpdateSettingsTask.PRIVACY_FRIENDS;
import static com.borqs.music.tasks.UpdateSettingsTask.PRIVACY_PRIVATE;
import static com.borqs.music.tasks.UpdateSettingsTask.PRIVACY_PUBLIC;
import static com.borqs.music.ui.SignupUploadActivity.AUTO_UPLOAD_DISABLE;
import static com.borqs.music.ui.SignupUploadActivity.PREFERENCE_KEY_SIGNUP_UPLOAD;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.widget.ListView;
import android.widget.Toast;

import com.borqs.music.R;
import com.borqs.music.TransferService;
import com.borqs.music.executor.MusicExecutor;
import com.borqs.music.executor.Task;
import com.borqs.music.executor.TaskAdapter;
import com.borqs.music.executor.TaskListener;
import com.borqs.music.tasks.QuerySettingsTask;
import com.borqs.music.tasks.UpdateSettingsTask;
import com.borqs.music.ui.online.OnlineDownloadingListActivity;
import com.borqs.music.util.AccountUtils;
import com.borqs.music.util.MusicConf.ServerSettingNames;
import com.borqs.music.util.MusicConf.SettingKeys;
import com.borqs.music.util.MusicUtils;
import com.borqs.music.util.MyLogger;
import com.borqs.music.util.SharedPreferencesCompat;

public class SettingsActivity extends PreferenceActivity implements SettingKeys {
    static final MyLogger logger = MyLogger.getLogger("SettingsActivity");

    private SharedPreferences mPreferences;
    private CheckBoxPreference mUploadFavorite;
    private Preference mUploadNow;
    private boolean isPrivacyLoaded = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);
        mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        Preference uploadPreference = findPreference(KEY_AUTO_UPLOAD_SONGS);
        uploadPreference.setOnPreferenceClickListener(mPreferenceClickLister);

        Preference privacyPreference = findPreference(KEY_MUSIC_SHARE_PRAVICY);
        privacyPreference.setOnPreferenceClickListener(mPreferenceClickLister);

        mUploadNow = findPreference(KEY_UPLOAD_SONGS_NOW);
        mUploadNow.setOnPreferenceClickListener(mPreferenceClickLister);

        mUploadFavorite = (CheckBoxPreference) findPreference(KEY_AUTO_UPLOAD_FAVORITES);

        Preference showDownloadingList = (Preference) findPreference(KEY_SHOW_DOWNLOADING_SONGS);
        showDownloadingList.setOnPreferenceClickListener(mPreferenceClickLister);
        mToast = Toast.makeText(this, R.string.app_name, Toast.LENGTH_LONG);

        int index = mPreferences.getInt(PREFERENCE_KEY_SIGNUP_UPLOAD, AUTO_UPLOAD_DISABLE);
        boolean isAudoLoadEnabled = (index != AUTO_UPLOAD_DISABLE);
        mUploadNow.setEnabled(isAudoLoadEnabled);
        mUploadFavorite.setEnabled(isAudoLoadEnabled);
    }

    private Preference.OnPreferenceChangeListener mMarkLastsongListener = new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            logger.d("mark last song listener, newValue is :" + newValue);
            Editor ed = mPreferences.edit();
            if (!(Boolean) newValue) {
                ed.remove("queue");
                ed.remove("cardid");
                ed.remove("curpos");
            }
            ed.putBoolean("mark_last_song", (Boolean) newValue);
            SharedPreferencesCompat.apply(ed);
            return true;
        }
    };

    private OnPreferenceClickListener mPreferenceClickLister = new OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference preference) {
            final String key = preference.getKey();

            if (KEY_SHOW_DOWNLOADING_SONGS.equals(key)) {
                Intent intent = new Intent(SettingsActivity.this,
                        OnlineDownloadingListActivity.class);
                startActivity(intent);
                return true;
            }

            if (KEY_AUTO_UPLOAD_SONGS.equals(key)) {
                Intent intent = new Intent(SettingsActivity.this, SignupUploadActivity.class);
                startActivityForResult(intent, REQ_CODE_SYNC);
                return true;
            }

            if (KEY_MUSIC_SHARE_PRAVICY.equals(key)) {
                if (!MusicUtils.checkBorqsAccount(SettingsActivity.this)) {
                    return true;
                }
                if (isPrivacyLoaded) {
                    handler.sendEmptyMessage(MSG_SHOW_PIVACY);
                } else {
                    getPrivacy();
                }
                return true;
            }

            if (KEY_UPLOAD_SONGS_NOW.equals(key)) {
                if (!MusicUtils.checkBorqsAccount(SettingsActivity.this)) {
                    return true;
                }
                Intent syncIntent = new Intent(TransferService.ACTION_START_UPLOAD_SONG);
                syncIntent.setClass(SettingsActivity.this, TransferService.class);
                startService(syncIntent);
                syncIntent.setAction(TransferService.ACTION_START_UPLOAD_LYRIC);
                startService(syncIntent);
                return true;
            }

            return false;
        }
    };

    private static final int REQ_CODE_SYNC = 1;

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK == resultCode && REQ_CODE_SYNC == requestCode) {
            boolean isEnable = data.getBooleanExtra("IS_ENABLE", false);
            mUploadFavorite.setEnabled(isEnable);
            mUploadNow.setEnabled(isEnable);
        }
    };

    private static final int DIALOG_SINGLE_CHOICE = 0;
    private static final int DIALOG_PROGRESS = 4;

    @Override
    protected Dialog onCreateDialog(int id, Bundle args) {
        switch (id) {
            case DIALOG_SINGLE_CHOICE:
                return new AlertDialog.Builder(this)
                        .setIcon(android.R.drawable.ic_dialog_info)
                        .setTitle(R.string.setting_music_pravicy)
                        .setSingleChoiceItems(R.array.music_pravicy_list, 0, null)
                        .setPositiveButton(R.string.alert_dialog_ok,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {
                                        AlertDialog singleChoice = (AlertDialog) dialog;
                                        ListView lv = singleChoice.getListView();
                                        int pos = lv.getCheckedItemPosition();
                                        int posOld = mPreferences.getInt(KEY_MUSIC_SHARE_PRAVICY,
                                                -1);
                                            if (pos == posOld) {
                                            return;
                                        }
                                        int privacy = positionToPrivacy(pos);
                                        updatePrivacy(privacy);
                                    }
                                })
                        .setNegativeButton(R.string.alert_dialog_cancel, null)
                        .create();
            case DIALOG_PROGRESS:
                ProgressDialog progress = new ProgressDialog(this);
                progress.setTitle(R.string.app_name);
                progress.setMessage(getString(R.string.setting_music_pravicy_sync));
                return progress;
        }
        return null;
    }

    @Override
    public void onPrepareDialog(int id, Dialog dialog, final Bundle args) {
        switch (id) {
            case DIALOG_SINGLE_CHOICE: {
                AlertDialog singleChoice = (AlertDialog) dialog;
                int pos = mPreferences.getInt(KEY_MUSIC_SHARE_PRAVICY, 0);
                singleChoice.getListView().setItemChecked(pos, true);
            }
        }
    }

    void updatePrivacy(int privacy) {
        handler.sendEmptyMessage(MSG_SHOW_PROGRESS);
        String ticket = AccountUtils.getUserData(this,
                AccountUtils.BORQS_ACCOUNT_OPTIONS_KEY_SESSION);
        UpdateSettingsTask task = new UpdateSettingsTask(updatePrivacyListener, ticket, privacy);
        MusicExecutor.executeTask(task);
    }

    void getPrivacy() {
        handler.sendEmptyMessage(MSG_SHOW_PROGRESS);
        String ticket = AccountUtils.getUserData(this,
                AccountUtils.BORQS_ACCOUNT_OPTIONS_KEY_SESSION);
        QuerySettingsTask task = new QuerySettingsTask(getPrivacyListener, ticket,
                ServerSettingNames.PRIVACY);
        MusicExecutor.executeTask(task);
    }

    private TaskListener updatePrivacyListener = new TaskAdapter() {

        @Override
        public void onDone(Task task) {
            int privacy = (Integer) task.getResult();
            int pos = privacyToPosition(privacy);

            Editor editor = mPreferences.edit();
            editor.putInt(KEY_MUSIC_SHARE_PRAVICY, pos);
            SharedPreferencesCompat.apply(editor);
            showToast(R.string.setting_music_pravicy_success);
            handler.sendEmptyMessage(MSG_HIDE_PROGRESS);
        }

        @Override
        public void onFail(Task task) {
            handler.sendEmptyMessage(MSG_HIDE_PROGRESS);
            if (!MusicUtils.checkSessionExpired(SettingsActivity.this,
                    task.getErrorReason().code)) {
                showToast(R.string.setting_music_pravicy_failed);
            }
        }
    };

    private TaskListener getPrivacyListener = new TaskAdapter() {

        @Override
        public void onDone(Task task) {
            int privacy = (Integer) task.getResult();
            int pos = privacyToPosition(privacy);

            Editor editor = mPreferences.edit();
            editor.putInt(KEY_MUSIC_SHARE_PRAVICY, pos);
            SharedPreferencesCompat.apply(editor);
            isPrivacyLoaded = true;
            handler.sendEmptyMessage(MSG_HIDE_PROGRESS);
            handler.sendEmptyMessage(MSG_SHOW_PIVACY);
        }

        @Override
        public void onFail(Task task) {
            handler.sendEmptyMessage(MSG_HIDE_PROGRESS);
            if (!MusicUtils.checkSessionExpired(SettingsActivity.this,
                    task.getErrorReason().code)) {
                showToast(R.string.setting_music_pravicy_failed);
            }
        }
    };

    int privacyToPosition(int privacy){
        int pos = 0;

        if (privacy == PRIVACY_PRIVATE) {
            pos = 0;
        } else if (privacy == PRIVACY_FRIENDS) {
            pos = 1;
        } else if (privacy == PRIVACY_PUBLIC) {
            pos = 2;
        }

        return pos;
    }

    int positionToPrivacy(int pos){
        int privacy = PRIVACY_PUBLIC;

        if (pos == 0) {
            privacy = PRIVACY_PRIVATE;
        } else if (pos == 1) {
            privacy = PRIVACY_FRIENDS;
        } else if (pos == 2) {
            privacy = PRIVACY_PUBLIC;
        }

        return privacy;
    }

    private Toast mToast;
    void showToast(int resId) {
        Message msg = handler.obtainMessage(MSG_SHOW_TOAST);
        msg.arg1 = resId;
        msg.sendToTarget();
    }

    private static final int MSG_SHOW_TOAST = 0;
    private static final int MSG_SHOW_PROGRESS = 1;
    private static final int MSG_HIDE_PROGRESS = 2;
    private static final int MSG_SHOW_PIVACY = 3;
    private static final int MSG_HIDE_PIVACY = 4;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SHOW_TOAST:
                    int resId = msg.arg1;
                    mToast.setText(resId);
                    mToast.show();
                    break;
                case MSG_SHOW_PROGRESS:
                    showDialog(DIALOG_PROGRESS);
                    break;
                case MSG_HIDE_PROGRESS:
                    dismissDialog(DIALOG_PROGRESS);
                    break;
                case MSG_SHOW_PIVACY:
                    showDialog(DIALOG_SINGLE_CHOICE);
                    break;
                case MSG_HIDE_PIVACY:
                    dismissDialog(DIALOG_SINGLE_CHOICE);
                    break;
            }
        }
    };
}
